/**
 * @author 太阳当空丶赵
 * @date 2022/11/30-16:23
 * @version 1.0.0
 * test
 */
const fs = require("fs")
const axios = require("axios")
const FormData = require("form-data")
const {wx} = require("../config")
// const getToken = require("./getToken")
/**
 * 上传文件到oss对象存储的方法
 * @filePath String, 要上传的文件地址
 * @cloudPath String, 上传到指定地址
 * */
module.exports = async function (filePath, cloudPath) {
    return new Promise(async (resolve, reject) => {
        try {
            // const access_token = getToken()

            // const getUploadPath = `https://api.weixin.qq.com/tcb/uploadfile?access_token=${access_token}` // 请求图片上传地址
            const getUploadPath = `http://api.weixin.qq.com/tcb/uploadfile` // 请求图片上传地址，云调用

            const data = {
                "env": wx.EnvId,
                "path": cloudPath
            }
            const res = await axios.post(getUploadPath, data)
            console.log("get upload url",res.data)
            const {url, token, authorization, cos_file_id, file_id} = res.data
            // 读取文件为二进制
            const blob = fs.readFileSync(filePath)
            console.info("file read")
            const form = new FormData()
            form.append("key", cloudPath)
            form.append("Signature", authorization)
            form.append("x-cos-security-token", token)
            form.append("x-cos-meta-fileid", cos_file_id)
            form.append("file", blob)
            const headers = form.getHeaders()
            form.getLength((err,length) => {
                if (err) return reject(false)
                headers['content-length'] = length
                axios.post(url,form,{headers}).then(result => {
                    console.log("upload file",result.data)
                    resolve(file_id)
                })

            })

        }catch (e){
            console.info("upload error",e)
            reject(false)
        }
    })
}


